import sys
import time
from Core import request_driver as webdriver
import config as conf


# 获取定期测试信息
def get_exam():
    # url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/regular/' \
    #       'index?lang=zh&utcoffset=-28800&exam_year=2021&sub_type=business&page=1&limit=16'
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/index?lang=zh&utcoffset=-28800&page=1&limit=10000'
    return MyReq.http_get_by_json(url)


# 获取考试试卷
def get_exam_paper(exam_id):
    unix_time = str(int(time.time()))
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/start?lang=zh&utcoffset=-28800&examId='\
          + exam_id + '&type=normal&start_time=' + unix_time
    return MyReq.http_get_by_json(url)


# 获取试卷答案
def get_exam_result(result_id):
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/' \
          'resultDetail?lang=zh&utcoffset=-28800&type=normal&resultId=' + result_id
    return MyReq.http_get_by_json(url)


# 发送答案参数
def post_exam(data):
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/finish?lang=zh&utcoffset=-28800'
    return MyReq.http_post_by_json(url, data)


# 获取答题结果
def get_result(exam_id):
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/detail?lang=zh&utcoffset=-28800&from=exam&examId=' + exam_id
    return MyReq.http_get_by_json(url)


# 远程过程认证
def auth():
    import requests
    url = 'https://www.my-aihome.cn/2021dingqiceshi-rs.json'
    response = requests.get(url,verify=False).json()
    if response['flag'] == 'True':
        return True
    else:
        sys.exit(0)



if __name__ == '__main__':
    print('程序正在启动....', end=' ')
    print('完成！')
    print('正在加载题库...', end=' ')
    print('完成！')
    MyReq = webdriver.DriverRequests(True, False)
    conf.Headers['Authorization'] = input("Authorization Code:")
    # # 认证
    # auth()

    while True:
        # 获取定期测试相关信息
        print('开始获取考试列表.....', end=' ')
        exam_res = get_exam()
        # print(exam_res)
        if exam_res['code'] == 'get_exam_list_success':
            print(exam_res['message'])
            for i, item in enumerate(exam_res['data']['list']):
                if item['pass_status'] != 'passed':
                    print('   序号:【' + str(i) + '】', '试题名称:' + item['title'])
        else:
            print('Authorization Code 错误或网络错误')
            sys.exit(0)

        # 根据列表号获取测试题UUID
        input_str = input('输入试卷序号(输入X退出程序)：')
        if input_str == 'x' or input_str == 'X':
            sys.exit(0)
        else:
            index_id = int(input_str)

        learn_time = input("输入答题时长(秒):")
        exam_uuid = exam_res['data']['list'][index_id]['uuid']
        print('开始作答:', exam_res['data']['list'][index_id]['title'], exam_uuid)

        # 获取试题
        print('获取题目....', end=' ')
        exam_paper_res = get_exam_paper(exam_uuid)
        print(exam_paper_res['message'])
        result_id = exam_paper_res['data']['resultId']

        # 获取试题答案
        print('查询答案....', end=' ')
        exam_answer_res = get_exam_result(result_id)['data']
        print('完毕!!!')

        # 组成试题答案，做为参数发送给服务器
        my_answer = {}

        my_answer['usedTime'] = learn_time
        my_answer['resultId'] = result_id
        my_answer['examId'] = exam_uuid
        my_answer['buildId'] = exam_paper_res['data']['buildId']
        my_answer['submitType'] = 'compel'
        my_answer['type'] = 'normal'

        exam_answer_items = exam_answer_res['items']
        for uuid, item in exam_answer_items.items():
            if item['type'] == 'material':
                # print('material UUID', item['uuid'])
                exam_answer_items_subs = item['subs']
                for sub_uuid, sub_item in exam_answer_items_subs.items():
                    for sub_answer_index, sub_answer_item in enumerate(sub_item['answer']):
                        my_answer['data[' + sub_uuid + '][' + str(sub_answer_index) + ']'] = sub_answer_item
            else:
                for answer_index, answer_item in enumerate(item['answer']):
                    my_answer['data[' + uuid + '][' + str(answer_index) + ']'] = answer_item

        for j in range(int(learn_time) - 1):
            x = int(learn_time) - j
            my_str = "正在作答 " + str(x)
            print(my_str, end='\r', flush=True)
            time.sleep(0.8)

        # 提交答案
        res = post_exam(my_answer)
        print('提交答案', res['message'])

        # 获取结果
        result = get_result(exam_uuid)
        print(result['data']['examUser']['dept_names'], '-----', result['data']['examUser']['user_name'])
        print('试卷名称', result['data']['info']['title'], '分数', result['data']['info']['total_score'])

        continue

    # 等待输入防止程序退出
    input('')



